package com.design.patterns.creativeModel.proxy;

import com.design.patterns.creativeModel.proxy.service.ThirdPartyYouTubeClass;
import com.design.patterns.creativeModel.proxy.service.downloader.YouTubeDownloader;
import com.design.patterns.creativeModel.proxy.service.proxy.YouTubeCacheProxy;

/**
 * 代理模式
 * 目的：为其他对象提供一种代理以控制对这个对象的访问。
 * 代理模式广泛应用，比如日志，权限，缓存等方面，包括spring中的AOP
 */
public class ProxyMain {
    public static void main(String[] args) {
        /**
         * 没有缓存的类，真实干活
         */
        YouTubeDownloader naiveDownloader = new YouTubeDownloader(new ThirdPartyYouTubeClass());
        /**
         * 带有缓存的代理类，客户端真实调用的是代理类
         */
        YouTubeDownloader smartDownloader = new YouTubeDownloader(new YouTubeCacheProxy());
        /**
         * 将这两个类加入到测试中
         */
        long naive = test(naiveDownloader);
        long smart = test(smartDownloader);
        /**
         * 有缓存比没有缓存快4707ms
         */
        System.out.print("Time saved by caching proxy: " + (naive - smart) + "ms");

    }

    private static long test(YouTubeDownloader downloader) {
        long startTime = System.currentTimeMillis();

        // 我们应用中的用户行为:
        downloader.renderPopularVideos();
        downloader.renderVideoPage("catzzzzzzzzz");
        downloader.renderPopularVideos();
        downloader.renderVideoPage("dancesvideoo");
        // 用户可能会经常访问同一页面.
        downloader.renderVideoPage("catzzzzzzzzz");
        downloader.renderVideoPage("someothervid");

        long estimatedTime = System.currentTimeMillis() - startTime;
        System.out.print("Time elapsed: " + estimatedTime + "ms\n");
        return estimatedTime;
    }
}
